import React, { Component } from 'react';
import { observable } from 'mobx';
import { observer, inject } from "mobx-react";
import PropTypes from 'prop-types';
import { Button, Modal, message } from 'antd';
import moment from 'moment';
import TabTitle from '@/components/TabTitle/TabTitle'
import FilterBar from './components/FilterBar/FilterBar'
import ChooseTips from '@/components/ChooseTips/ChooseTips';
import NewsPreview from '@/components/NewsPreview/NewsPreview'
import HistoryTable from './components/HistoryTable/HistoryTable'
import http from '../../../common/http';

const confirm = Modal.confirm;

function PreviewFooter(props) {
  const previewType = props.previewType
  const previewStatus = props.previewStatus
  const previewTop = props.previewTop

  switch (previewType) {
    case 0:
      switch (previewStatus) {
        case 0:
          return (
            [
              <Button
                className="btn95 ml10"
                onClick={props.showRejectConfirm}>Reject</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.showApproveConfirm}>Approve</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.toEdit}>Edit</Button>
            ]
          )
        case 1:
          return (
            [
              <Button
                className="btn95 ml10"
                onClick={props.showDeleteConfirm}>Delete</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.showReapproveConfirm}>Reapprove</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.toEdit}>Edit</Button>
            ]
          )
        case 2:
          return (
            [
              <Button
                className="btn95 ml10"
                onClick={props.showRemoveConfirm}>Remove</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.showTopConfirm}>
                {
                  !previewTop ?
                  'Top' : 'Revoke'
                }
                </Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.toEdit}>Edit</Button>
            ]
          )
        default:
          return null
      }
    case 2:
      switch (previewStatus) {
        case 0:
          return (
            [
              <Button
                className="btn95 ml10"
                onClick={props.showDeleteConfirm}>Delete</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.showReleaseConfirm}>Release</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.toEdit}>Edit</Button>
            ]
          )
        default:
          return (
            [
              <Button
                className="btn95 ml10"
                onClick={props.showDeleteConfirm}>Delete</Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.showTopConfirm}>
                {
                  !previewTop ?
                  'Top' : 'Revoke'
                }
                </Button>,
              <Button
                type="primary"
                className="btn95 ml10"
                onClick={props.toEdit}>Edit</Button>
            ]
          )
      }
    default:
      return null
  }
}

@inject('rootStore') @observer
class HistoryNews extends Component {
  @observable tabKey = 1;
  @observable filterParam = {
    title: '',
    press: '',
    startTime: '',
    endTime: ''
  }
  @observable categoryActiveItem = ""
  @observable categoryStatus = true

  @observable showPreviewModal = false;
  @observable newsListDetails = {};
  @observable selectedRowsLength = 0;
  @observable selectedRowKeys = [];
  @observable categoryStatus: false;
  @observable previewId = 0;
  @observable previewStatus = "";
  @observable previewType = "";

  state = {
    timeValue: [],
  }

  componentDidMount() {
    document.getElementsByClassName('ant-layout-content')[0].scrollTop = 0
    this.toGetList();
    this.toGetCategory();
  }

  toGetList = () => {
    const newsStore = this.props.rootStore.newsStore;

    newsStore.toChangeListStatus("", "");
  }

  toGetCategory = () => {
    const newsStore = this.props.rootStore.newsStore;
    if (!newsStore.categoryFiftyLoadSuccess) {
      newsStore.toGetNewsCategoryFifty('en');
    }
  }

  toChooseCategory = (name, id) => {
    const newsStore = this.props.rootStore.newsStore;
    this.categoryActiveItem = name;
    newsStore.toChangeCategoryFilter(name, id)
  }

  toChangeCategoryStatus = () => {
    this.categoryStatus = !this.categoryStatus
  }

  filterBarSearch = () => {
    const newsStore = this.props.rootStore.newsStore;
    newsStore.filterParamSearch(this.filterParam);
  }

  titleValueOnChange = (e) => {
    this.filterParam.title = e.target.value;
  }

  timeOnChange = (value) => {
    this.filterParam.startTime = moment(value[0]).format('YYYY-MM-DD HH:mm');
    this.filterParam.endTime = moment(value[1]).format('YYYY-MM-DD HH:mm');
  }

  timeChange = (value, dateString) => {
    this.setState({
      timeValue: value
    })
  }

  filterBarReset = () => {
    const newsStore = this.props.rootStore.newsStore;
    this.filterParam.title = '';
    this.filterParam.press = '';
    this.filterParam.startTime = '';
    this.filterParam.endTime = '';
    this.categoryActiveItem = ""

    this.setState({
      timeValue: []
    })

    newsStore.filterParamSearch(this.filterParam);
  }

  toPreview = (record, status, type, top) => {
    this.previewId = record.id
    this.previewStatus = status;
    this.previewType = type;
    this.previewTop = top;
    this.newsListDetails = record;
    this.showPreviewModal = true
  }

  newsPrevieCancel = () => {
    this.showPreviewModal = false
  }

  toEdit = (id) => {
    const { history } = this.props;

    history.push(`/english/newsedit/${id}`)
  }

  pageOnChange = (pageNumber, pageSize) => {
    const newsStore = this.props.rootStore.newsStore;

    newsStore.toChangePageNumber(pageNumber)
  }

  pageSizeOnChange = (current, pageSize) => {
    const newsStore = this.props.rootStore.newsStore;

    newsStore.toChangePageSize(pageSize)
  }

  selectedRowsLengthChange = (length) => {
    this.selectedRowsLength = length
  }

  clearChooseTips = () => {
    this.selectedRowKeys = []
    this.selectedRowsLength = 0;
  }

  clearSelectRows = () => {
    this.selectedRowKeys = [];
    this.selectedRowsLength = 0;
  }

  showApproveConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    confirm({
      title: 'Are you sure approve this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const param = {
          ids: id
        }

        http.post('/article/online', param)
        .then((response) => {
          if (response.success) {
            that.showPreviewModal = false;
            message.success('Success');
            newsStore.toGetNewsList();
            that.clearSelectRows();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  showBatchApproveConfirm = () => {
    const newsStore = this.props.rootStore.newsStore;
    const keys = this.selectedRowKeys.join()
    const that = this
    if (this.selectedRowKeys.length !== 0) {
      confirm({
        title: 'Are you sure approve this news?',
        content: 'You can reapprove it in unavailable list',
        okText: 'Confirm',
        cancelText: 'Cancel',
        centered: true,
        onOk() {
          const param = {
            ids: keys
          }

          http.post('/article/online', param)
          .then((response) => {
            if (response.success) {
              message.success('Success');
              newsStore.toGetNewsList();
              that.clearSelectRows();
            }
          })
        },
        onCancel() {
        },
      });
    } else {
      message.warning('Please select at least one');
    }
  }

  showRejectConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    confirm({
      title: 'Are you sure reject this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const param = {
          ids: id.toString()
        }

        http.post('/article/reject', param)
        .then((response) => {
          if (response.success) {
            that.showPreviewModal = false;
            message.success('Success');
            newsStore.toGetNewsList();
            that.clearSelectRows();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  showTopConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    if (this.previewTop) {
      confirm({
        title: 'Are you sure revoke this news?',
        content: 'You can reapprove it in unavailable list',
        okText: 'Confirm',
        cancelText: 'Cancel',
        centered: true,
        onOk() {
          const param = {
            id: id
          }

          http.post('/article/cancel', param)
          .then((response) => {
            if (response.success) {
              message.success('Success');
              newsStore.toGetNewsList();
              that.showPreviewModal = false;
              that.clearSelectRows();
            }
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      confirm({
        title: 'Are you sure top this news?',
        content: 'You can reapprove it in unavailable list',
        okText: 'Confirm',
        cancelText: 'Cancel',
        centered: true,
        onOk() {
          const param = {
            id: id
          }

          http.post('/article/top', param)
          .then((response) => {
            if (response.success) {
              message.success('Success');
              newsStore.toGetNewsList();
              that.showPreviewModal = false;
              that.clearSelectRows();
            }
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  }

  showCancelTopConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    confirm({
      title: 'Are you sure revoke this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const param = {
          id: id
        }

        http.post('/article/cancel', param)
        .then((response) => {
          if (response.success) {
            message.success('Success');
            newsStore.toGetNewsList();
            that.clearSelectRows();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  showRemoveConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    confirm({
      title: 'Are you sure remove this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const param = {
          ids: id
        }

        http.post('/article/offline', param)
        .then((response) => {
          if (response.success) {
            message.success('Success');
            newsStore.toGetNewsList();
            that.showPreviewModal = false;
            that.clearSelectRows();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  showBatchRemoveConfirm = () => {
    const newsStore = this.props.rootStore.newsStore;
    const keys = this.selectedRowKeys.join()
    const that = this
    if (this.selectedRowKeys.length !== 0) {
      confirm({
        title: 'Are you sure remove these news?',
        content: 'You can reapprove it in unavailable list',
        okText: 'Confirm',
        cancelText: 'Cancel',
        centered: true,
        onOk() {
          const param = {
            ids: keys
          }

          http.post('/article/offline', param)
          .then((response) => {
            if (response.success) {
              message.success('Success');
              newsStore.toGetNewsList();
              that.clearSelectRows();
            }
          })
        },
        onCancel() {
        },
      });
    } else {
      message.warning('Please select at least one');
    }
  }

  showDeleteConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    confirm({
      title: 'Are you sure remove this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const param = {
          ids: id
        }

        http.post('/article/delete', param)
        .then((response) => {
          if (response.success) {
            message.success('Success');
            newsStore.toGetNewsList();
            that.showPreviewModal = false;
            that.clearSelectRows();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  showBatchDeleteConfirm = () => {
    const newsStore = this.props.rootStore.newsStore;
    const keys = this.selectedRowKeys.join()
    const that = this
    if (this.selectedRowKeys.length !== 0) {
      confirm({
        title: 'Are you sure remove these news?',
        content: 'You can reapprove it in unavailable list',
        okText: 'Confirm',
        cancelText: 'Cancel',
        centered: true,
        onOk() {
          const param = {
            ids: keys
          }

          http.post('/article/delete', param)
          .then((response) => {
            if (response.success) {
              message.success('Success');
              newsStore.toGetNewsList();
              that.clearSelectRows();
            }
          })
        },
        onCancel() {
        },
      });
    } else {
      message.warning('Please select at least one');
    }
  }

  showReapproveConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    confirm({
      title: 'Are you sure reapprove this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const param = {
          ids: id
        }

        http.post('/article/online', param)
        .then((response) => {
          if (response.success) {
            that.showPreviewModal = false;
            message.success('Success');
            newsStore.toGetNewsList();
            that.clearSelectRows();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  showReleaseConfirm = (id, props, that) => {
    const newsStore = this.props.rootStore.newsStore;
    confirm({
      title: 'Are you sure release this news?',
      content: 'You can reapprove it in unavailable list',
      okText: 'Confirm',
      cancelText: 'Cancel',
      centered: true,
      onOk() {
        const param = {
          ids: id
        }

        http.post('/article/online', param)
        .then((response) => {
          if (response.success) {
            that.showPreviewModal = false;
            message.success('Success');
            newsStore.toGetNewsList();
            that.clearSelectRows();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  static propTypes = {
    history: PropTypes.object.isRequired
  }

  render() {
    const newsStore = this.props.rootStore.newsStore;
    const selectedRowKeys = this.selectedRowKeys;
    const breadCrumb = ['News', 'History News']

    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRowsLength  = selectedRows.length;
      },
    };

    return (
      <div className="history-news">
        <TabTitle
          title="History News"
          breadCrumb={breadCrumb} />
          <div className="page-content mt144">
            <FilterBar
              filterBarSearch={this.filterBarSearch}
              titleValueOnChange={this.titleValueOnChange}
              titleValue={this.titleValue}
              timeOnChange={this.timeOnChange}
              timeChange={this.timeChange}
              timeValue={this.timeValue}
              filterBarReset={this.filterBarReset}
              categoryListFifty={newsStore.categoryListFifty}
              activeItem={this.categoryActiveItem}
              categoryStatus={this.categoryStatus}
              toChangeCategoryStatus={this.toChangeCategoryStatus}
              toChooseCategory={(name, id) => this.toChooseCategory(name, id)}
            />
            <div className="list-table">
              <div className="config-btn-group">
                <Button
                  type="primary"
                  className="config-btn"
                  onClick={this.showBatchApproveConfirm}>Batch Approve</Button>
                <Button
                  type="primary"
                  className="config-btn"
                  onClick={this.showBatchDeleteConfirm}>Batch Delete</Button>
                <Button
                  type="primary"
                  className="config-btn"
                  onClick={this.showBatchRemoveConfirm}>Batch Remove</Button>
              </div>
              <ChooseTips
                tipsNumber={this.selectedRowsLength}
                clearChooseTips={this.clearChooseTips} />
              <HistoryTable
                toEdit={(id) => this.toEdit(id)}
                toPreview={(record, status, type, top) => this.toPreview(record, status, type, top)}
                approve={(id) => this.showApproveConfirm(id, this.props, this)}
                reject={(id) => this.showRejectConfirm(id, this.props, this)}
                top={(id) => this.showTopConfirm(id, this.props, this)}
                cancelTop={(id) => this.showCancelTopConfirm(id, this.props, this)}
                release={(id) => this.showReleaseConfirm(id, this.props, this)}
                remove={(id) => this.showRemoveConfirm(id, this.props, this)}
                delete={(id) => this.showDeleteConfirm(id, this.props, this)}
                reapprove={(id) => this.showReapproveConfirm(id, this.props, this)}
                dataSource={newsStore.newsList}
                dataTotal={newsStore.newsListTotal}
                pageOnChange={this.pageOnChange}
                pageSizeOnChange={this.pageSizeOnChange}
                pageCurrent={newsStore.newsListParam.pageIndex}
                rowSelection={rowSelection}
              />
              <Modal
                title="News Preview"
                width={1165}
                visible={this.showPreviewModal}
                onCancel={this.newsPrevieCancel}
                footer={
                  <PreviewFooter
                    previewStatus={this.previewStatus}
                    previewType={this.previewType}
                    previewTop={this.previewTop}
                    toEdit={() => this.toEdit(this.previewId)}
                    showRejectConfirm={() => this.showRejectConfirm(this.previewId, this.props, this)}
                    showApproveConfirm={() => this.showApproveConfirm(this.previewId, this.props, this)}
                    showDeleteConfirm={() => this.showDeleteConfirm(this.previewId, this.props, this)}
                    showReapproveConfirm={() => this.showReapproveConfirm(this.previewId, this.props, this)}
                    showRemoveConfirm={() => this.showRemoveConfirm(this.previewId, this.props, this)}
                    showTopConfirm={() => this.showTopConfirm(this.previewId, this.props, this)}
                    showReleaseConfirm={() => this.showReleaseConfirm(this.previewId, this.props, this)}
                  />
                }>
                <NewsPreview newsListDetails={this.newsListDetails} />
              </Modal>
            </div>
          </div>
      </div>
    )
  }
}

export default HistoryNews;
